import { Upload, message } from "antd";
import type { UploadFile, UploadProps } from "antd/es/upload/interface";
import { PlusOutlined, LoadingOutlined } from "@ant-design/icons";
import { useEffect, useState } from "react";

interface UploadImageProps {
	value?: string;
	onChange?: (url: string) => void;
	maxSize?: number; // 单位：MB
}

const UploadImage = ({ value, onChange, maxSize = 2 }: UploadImageProps) => {
	const [fileList, setFileList] = useState<UploadFile[]>([]);
	const [loading, setLoading] = useState(false);

	useEffect(() => {
		if (value) {
			setFileList([
				{
					uid: "-1",
					name: "图片",
					status: "done",
					url: value.startsWith("http")
						? value
						: `${import.meta.env.VITE_APP_BASE_API}${value}`,
				},
			]);
		} else {
			setFileList([]);
		}
	}, [value]);

	const uploadProps: UploadProps = {
		action: `${import.meta.env.VITE_APP_BASE_API}/common/upload`,
		accept: "image/*",
		beforeUpload: (file: File) => {
			const isImage = file.type.startsWith("image/");
			if (!isImage) {
				message.error("只能上传图片文件！");
				return false;
			}
			const isLtSize = file.size / 1024 / 1024 < maxSize;
			if (!isLtSize) {
				message.error(`图片大小不能超过${maxSize}MB！`);
				return false;
			}
			setLoading(true);
			return true;
		},
		onChange: (info) => {
			const { status } = info.file;

			// 更新 fileList
			setFileList([...info.fileList]);

			if (status === "uploading") {
				setLoading(true);
				return;
			}

			if (status === "done") {
				const response = info.file.response;
				setLoading(false);
				if (response?.status === 0) {
					onChange?.(response.data.url);
					message.success(response.message || "上传成功");
				} else {
					setFileList([]);
					message.error(response?.message || "上传失败");
				}
			} else if (status === "error") {
				setFileList([]);
				setLoading(false);
				message.error("上传失败");
			} else if (status === "removed") {
				setFileList([]);
				setLoading(false);
				onChange?.("");
			}
		},
		onRemove: () => {
			setFileList([]);
			setLoading(false);
			onChange?.("");
			return true;
		},
		maxCount: 1,
		listType: "picture-card",
		fileList: fileList,
		showUploadList: {
			showPreviewIcon: true,
			showRemoveIcon: true,
		},
	};

	return (
		<Upload {...uploadProps}>
			{fileList.length < 1 && (
				<div>
					{loading ? <LoadingOutlined /> : <PlusOutlined />}
					<div style={{ marginTop: 8 }}>{loading ? "上传中..." : "上传"}</div>
				</div>
			)}
		</Upload>
	);
};

export default UploadImage;
